import { RootState } from '@/types/store'
import { Input, NavBar, TextArea } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import styles from './index.module.scss'
type Props = {
    onUpdate:(type:string, value:string) => void,
    hideInput: () => void,
    type: '' | 'name' | 'intro'
}
const EditInput = ({ hideInput, type, onUpdate }:Props) => {
  // 保存状态
  const userProfile = useSelector((state: RootState) => state.profile.userProfile)
  const [value, setValue] = useState(() => {
    return type === 'name' ? userProfile.name : userProfile.intro
  })

  const inputRef = useRef<InputRef>(null)
  const textAreaRef = useRef<TextAreaRef>(null)

  const onClick = () => {
    // todo 判断是否为空
    onUpdate(type, value)
  }
  useEffect(() => {
    inputRef.current?.focus()
    textAreaRef.current?.focus()

    // 原生的dom操作
    document.querySelector('textarea')?.setSelectionRange(-1, -1)

    return () => {
      console.log('销毁....')
    }
  }, [])
  return (
    <div className={styles.root}>
      <NavBar onBack={hideInput} className="navbar" right={<span className="commit-btn" onClick={onClick}>提交</span>}>
        编辑 {type === 'name' ? '昵称' : '简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>{type === 'name' ? '昵称' : '简介'}</h3>
        {
            type === 'name'
              ? (<div className="input-wrap">
            <Input ref={inputRef} placeholder="请输入" value={value} onChange={(e) => setValue(e)} />
          </div>)
              : (<TextArea
            className="textarea"
            ref={textAreaRef}
            placeholder="请输入简介"
            showCount
            value={value}
            onChange={e => setValue(e)}
            maxLength={99}
          />)
        }
      </div>
    </div>
  )
}

export default EditInput
